<template>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="600">
    <el-form
      ref="employeeFormRef"
      :model="employeeForm"
      :rules="employeeFormRules"
      label-width="100"
      status-icon
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="employeeForm.username" />
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="employeeForm.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="employeeForm.phone" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="employeeForm.sex">
          <el-radio value="1" label="1">男</el-radio>
          <el-radio value="0" label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="员工号" prop="idNumber">
        <el-input v-model="employeeForm.idNumber" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineOptions, defineExpose, defineEmits, nextTick } from 'vue'
import { reqAddEmployee, reqUpdateEmployee } from '@/api/employee'
import { ElMessage } from 'element-plus'

defineOptions({
  name: 'EmployeeAddEdit'
})

const dialogFormVisible = ref(false)

// 打开对话框
const dialogTitle = ref('新增员工')
const openDialog = (employee) => {
  //根据是否有 id 确定是新增? 修改?
  if (!employee) {
    //新增
    actionType.value = 'add'
    dialogTitle.value = '新增员工'
    employeeForm.value = {
      username: '',
      name: '',
      phone: '',
      sex: '1',
      idNumber: '',
      status: 1 //默认启用
    }
    //清空校验
    // 注意 clearValidate 是对 DOM 的操作，需要在 nextTick 内实现，以避免不生效的问题
    nextTick(() => {
      employeeFormRef.value.clearValidate()
    })
    //
  } else {
    //修改
    actionType.value = 'update'
    dialogTitle.value = '修改员工'
    // console.log('编辑：', employee)
    employeeForm.value = { ...employee }
  }
  dialogFormVisible.value = true
}
// 注意：defineExpose中暴露的函数，一定要写在defineExpose前面
defineExpose({
  openDialog
})

//员工
const employeeForm = ref({
  username: '',
  name: '',
  phone: '',
  sex: '1',
  idNumber: '',
  status: 1 //默认启用
})

const employeeFormRules = ref({
  username: [
    {
      required: true,
      message: '请输入员工的登录账号',
      trigger: 'blur'
    },
    { min: 4, max: 20, message: '账号长度必须 4 至 20', trigger: 'blur' }
  ],
  name: [
    {
      required: true,
      message: '请输入员工姓名',
      trigger: 'blur'
    },
    { min: 2, max: 6, message: '姓名长度必须 2 至 6', trigger: 'blur' }
  ],
  phone: [
    {
      required: true,
      validator: (rules, value, callback) => {
        //3个参数分别是：验证规则信息、输入框的值、通过验证规则的回调
        if (!value) {
          callback(new Error('请输入手机号'))
        } else {
          const reg = /^1[345789]\d{9}$/
          if (reg.test(value)) {
            callback()
          } else {
            callback(new Error('手机号格式不正确'))
          }
        }
      },
      trigger: 'blur'
    }
  ],
  idNumber: [
    { required: true, message: '请输入员工号码', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{3,17}$/,
      message: '员工号码格式不正确',
      trigger: 'blur'
    }
  ]
})

//提交保存
const actionType = ref('add')
const employeeFormRef = ref()
const emits = defineEmits(['empAddEditSuccess'])
const onSubmit = () => {
  employeeFormRef.value.validate(async (vaild) => {
    if (vaild) {
      // 验证通过,继续

      if (actionType.value === 'add') {
        const res = await reqAddEmployee(employeeForm.value)
        //新增
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg || '创建员工成功！')
          //关闭窗口
          dialogFormVisible.value = false
          //派发事件 addSuccess
          emits('empAddEditSuccess')
        } else {
          ElMessage.error(res.data.msg || '创建员工失败！')
        }
      } else {
        //修改
        const res = await reqUpdateEmployee(employeeForm.value)
        if (res.data.code === 200) {
          ElMessage.success(res.data.msg || '修改员工成功！')
          //关闭窗口
          dialogFormVisible.value = false
          //派发事件 addSuccess
          emits('empAddEditSuccess')
        } else {
          ElMessage.error(res.data.msg || '修改员工失败！')
        }
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped></style>
